/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;
import beans.Rezervacija;

import java.sql.*;
import java.util.Calendar;
import java.util.Vector;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.faces.component.UIComponent;
import javax.faces.validator.ValidatorException;

import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.http.*;

public class User {
    private String username;
    private String password;
    private String checkpassword;
    private int kid;
    private String ime;
    private String prezime;
    private String email;
    private String outcome;
    private Vector<Rezervacija> rezervacije;
    private String funkcija ;
    private int isAdmin;

    public String getCheckpassword() {
        return checkpassword;
    }

    public void setCheckpassword(String checkpassword) {
        this.checkpassword = checkpassword;
    }

    public Vector<Rezervacija> getRezervacije() {
        return rezervacije;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
     public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getKid() {
        return kid;
    }

    public void setKid(int kid) {
        this.kid = kid;
    }

    public String getIme() {
        return ime;
    }

    public void setIme(String ime) {
        this.ime = ime;
    }

    public String getPrezime() {
        return prezime;
    }

    public void setPrezime(String prezime) {
        this.prezime = prezime;
    }
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    public String getFunkcija() {
        return funkcija;
    }

    public void setFunkcija(String funkcija) {
        this.funkcija = funkcija;
    }

    public void validateEmail(FacesContext context,UIComponent componentToValidate, Object value) throws ValidatorException {
             String email1=(String)value;
   		     int i= email1.indexOf('@');
             int j=email1.indexOf('.',i+2);
             int k=email1.length();
             if(i>1 && j>0 && k>j+1) return; //ok e-mail adresa

            FacesMessage message=new FacesMessage("Неправилно унета ел. пошта!");
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
        //  context.addMessage(componentToValidate.getClientId(context), message);
        //    prethodna linija koda je zakomentarisana, jer se radi automatski
        //    bacanjem odgovarajuceg Exception-a
			throw new ValidatorException(message);
    }

    public String register() {
        outcome = null;
        Connection con = null;
        ResultSet rs = null;
        ResultSet rs2 = null;
        Statement stmt = null;
        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from korisnik where username='" + username + "';");
            
            if (rs.next()) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Изабрали сте већ постојеће корисничко име!Покушајте поново са други корисничким именом"));
                setOutcome("registracija");
            }  else if(!password.equals(checkpassword)){
                 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Лозинка и потврда лозинке нису иста!"));
                 setOutcome("registracija");
            }
              else{
                rs = stmt.executeQuery("select * from zahtevi_registracije where username='" + username + "';");
                 if (rs.next()) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Kорисничко име се већ разматра или је одбијено !  Покушајте поново са други корисничким именом"));
                    setOutcome("registracija");
                }else{
                    Timestamp ts = new Timestamp(Calendar.getInstance().getTimeInMillis());
                    stmt.executeUpdate("insert into zahtevi_registracije (username,lozinka,ime,prezime,email,funkcija,vreme_zahteva) values ('" + username + "' ,'" + password + "' ,'" + ime + "' ,'" + prezime + "' ,'" + email + "' ,'" + funkcija + "' ,'" + ts + "');");
                    username="";password="";ime="";prezime="";email="";funkcija="";
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ваш захтев је узет у разматрање!"));
                    setOutcome("registracija");
                }
            }
            stmt.close();
            con.close();

        } catch (Exception e) {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {
                }
            }
            setOutcome("error");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getLocalizedMessage()));
        }
        return outcome;
    }



    public String login() {
        outcome = null;
        Connection con = null;
        ResultSet rs = null;
        Statement stmt = null;
        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from zahtevi_registracije where username='" + username + "' and lozinka='" + password + "';");
            
            
            if (rs.next()){
                int i= rs.getInt("status");
                if(i==2){FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ваш захтев је одбијен и нећете моћи да се логујете!"));}
                else if(i==0){username=password="";FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Ваш захтев је тренутно у разматранју! Молимо покусајте касније!"));}}
            else{
            rs = stmt.executeQuery("select * from korisnik where username='" + username + "' and lozinka='" + password + "';");
            if (rs.next()) {
                kid = rs.getInt("kid");
                email = rs.getString("email");
                ime = rs.getString("ime");
                prezime = rs.getString("prezime");
                funkcija= rs.getString("funkcija");
                isAdmin= rs.getInt("isAdmin");
                postaviRezervacije();
                if (isAdmin==1) {
                    setOutcome("admin");
                } else {
                    setOutcome("user");
                }
                } else {
                 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Неисправно корисничко име или лозинка!"));
            }
            }
            stmt.close();
            con.close();

        } catch (Exception e) {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {
                }
            }
            setOutcome("error");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getLocalizedMessage()));
        }
        return outcome;
    }
    public void postaviRezervacije(){
        Connection con = null;
        ResultSet rs = null;
        ResultSet rs1 = null;
        Statement stmt = null;
        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from rezervacija where korisnik=" + kid + ";");
            rezervacije=new Vector<Rezervacija>();
            ArrayList<Integer> list = new ArrayList<Integer>();
            while(rs.next()){
                String sid=rs.getString("sid");
                int ssid=Integer.parseInt(sid);
                //int sid=rs.getInt("sid");
                list.add(ssid);
                Rezervacija r=new Rezervacija();
                r.setRid(rs.getInt("rid"));
                r.setNamena(rs.getString("namena"));
                r.setDatum(rs.getString("datum"));
                r.setDatum_rezervacije(rs.getString("datumRezervisanja"));
                r.setPocev_od(rs.getString("PocevOd"));
                r.setTrajanje(rs.getString("Trajanje"));
                rezervacije.add(r);
            }
            postaviImenaSala(list);
            
        } catch (Exception e) {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {
                }
            }
            setOutcome("error");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getLocalizedMessage()));
        }

    }
    public void postaviImenaSala(ArrayList<Integer> list){
        Connection con = null;
        ResultSet rs = null;
        Statement stmt = null;
        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            for(int i=0;i<list.size();i++){
               int sid=list.get(i);
               rs = stmt.executeQuery("select * from sala where sid = "+sid+";");
               Rezervacija r=rezervacije.get(i);
               if(rs.next())r.setSala(rs.getString("naziv"));
            }
        } catch (Exception e) {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {
                }
            }
            setOutcome("error");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getLocalizedMessage()));
        }
    }
 
    public void setOutcome(String outcome) {
        this.outcome = outcome;
    }
      public String getOutcome() {
        return outcome;
    }
    public String klogout() {
        setOutcome("index");
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        session.invalidate();
        return outcome;
    }
    public String kpregled() {
        setOutcome("pregled");
        return "user";
    }

    public String kpocetna() {
        setOutcome("user");
        return "user";
    }
    public String klab() {
        setOutcome("laboratorije");
        return "user";
    }

    public String alab() {
        setOutcome("prostorije");
        return "admin";
    }

     public String klabkonkretna() {
        setOutcome("lab");
        return "user";
    }

    public String alabkonkretna() {
        setOutcome("lab");
        return "admin";
    }
    
    public String ktabela() {
        setOutcome("tabela");
        return "user";
    }

    public String krezervisanje() {
        setOutcome("rezervisanje");
        return "user";
    }

    public String kraspored(){
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        session.setAttribute("datumi", null);
        session.setAttribute("dani", null);
        setOutcome("kraspored");
        return "user";
    }

    public String kprez() {
        setOutcome("kpregledrez");
        return "user";
    }

    public String brisiRezervacije(){
        String vrati="user";
        Connection con = null;
        ResultSet rs = null;
        Statement stmt = null;
        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            Enumeration parametri = request.getParameterNames();
            int removed = 0;
            while (parametri.hasMoreElements()) {
                String parametar = (String) parametri.nextElement();
                int i =0;
                boolean dalje=true;
                try {
                    i = Integer.parseInt(parametar);
                } catch (NumberFormatException nfe) {dalje=false;
                }
                if(dalje==true){
                Rezervacija r = rezervacije.remove(i-removed);//zato sto idu po redu
                removed++;
                String upit = "delete from rezervacija where rid=" + r.getRid() + ";";
                stmt.executeUpdate(upit);
                }
            }
            stmt.close();
            con.close();
            setOutcome("pregled");
            return(vrati);

          } catch (Exception e) {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {
                }
            }
            vrati="error";
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getLocalizedMessage()));
            return vrati;
        }

    }
    public String alogout() {
        setOutcome("index");
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        session.invalidate();
        return outcome;
    }

    public String apocetna() {
        setOutcome("admin");
        return "admin";
    }

    public String anovi() {
        setOutcome("novik");
        return "admin";
    }

    public String apraznik() {
        setOutcome("praznik");
        return "admin";
    }
    public String aprostorije() {
        setOutcome("prostorije");
        return "admin";
    }

    public String apregledzahteva() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        Connection con = null;
        ResultSet rs = null;
        Statement stmt = null;
        try {
            ArrayList<Zahtev> reqs = new ArrayList<Zahtev>();
            con = DB.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from zahtevi_registracije where status='"+0+"';");
            while(rs.next()){
                reqs.add( new Zahtev(
                                   rs.getString("username"),
                                   rs.getString("lozinka"),
                                   rs.getString("ime"),
                                   rs.getString("prezime"),
                                   rs.getString("email"),
                                   rs.getString("funkcija"),
                                   rs.getTimestamp("vreme_zahteva")
                                   )
                         );
            }
            session.setAttribute("zahtevi", reqs);
            stmt.close();con.close();
        }catch (Exception e) {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {}
            }
            context.addMessage(null, new FacesMessage(e.getLocalizedMessage()));
        }
        setOutcome("zahtevi");
        return "admin";
    }

    public String apregledkor() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        Connection con = null;
        ResultSet rs = null;
        Statement stmt = null;
        try {
            ArrayList<Korisnik> kor = new ArrayList<Korisnik>();
            con = DB.getConnection();
            stmt = con.createStatement();
            int ad=0;
            rs = stmt.executeQuery("select * from korisnik where isAdmin="+ad+";");
            while(rs.next()){
                kor.add( new Korisnik(
                                   rs.getInt("kid"),
                                   rs.getString("username"),
                                   rs.getString("lozinka"),
                                   rs.getString("ime"),
                                   rs.getString("prezime"),
                                   rs.getString("email"),
                                   rs.getString("funkcija")
                                   )
                         );
            }
            session.setAttribute("korisnici", kor);
            stmt.close();con.close();
        }catch (Exception e) {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {}
            }
            context.addMessage(null, new FacesMessage(e.getLocalizedMessage()));
        }
        setOutcome("korisnici");
        return "admin";
    }

    public String asalaprom() {
        setOutcome("salapromena");
        return "admin";
    }

    public String adminuserp() {
        setOutcome("adminuser");
        return "admin";
    }

    public String admkorrezervisi() {
        setOutcome("admkorrez");
        return "admin";
    }




}
